<?php

namespace app\common\model;

use think\Model;

class Trade extends Model
{
    // 表名
    protected $name = 'trade';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $insert = ['surplusnum','status'=>'0'];  

    // 追加属性
    protected $append = [
        'action_text',
        'finishtime_text',
        'status_text'
    ];

    protected $type = [
        'finish'  =>  'timestamp',
    ];

    public function setSurplusnumAttr()
    {
        return input('post.num/d');
    }
    
    public function getActionList()
    {
        return ['1' => __('Action 1'),'2' => __('Action 2')];
    }     

    public function getStatusList()
    {
        return ['0' => __('Status 0'),'1' => __('Status 1'),'2' => __('Status 2'),'3' => __('Status 3'),'4' => __('Status 4'),'5' => __('Status 5')];
    }     


    public function getActionTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['action'];
        $list = $this->getActionList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getFinishtimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['finishtime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setFinishtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->field('id,username')->setEagerlyType(0);
    }
}
